package com.jcsz.gulimall.product.web;

import com.jcsz.gulimall.product.entity.CategoryEntity;
import com.jcsz.gulimall.product.service.CategoryService;
import com.jcsz.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: IndexController
 * @author: 一把Po吉他
 * @date: 2022/10/31 10:13
 * @version: 1.0
 **/
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String getIndex(Model model) {
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Catagories();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatlogJson() {
        Map<String, List<Catelog2Vo>> categoryVos = categoryService.getCatlogJson();
        return categoryVos;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        System.out.println("获取锁" + Thread.currentThread().getId());
        try {
            TimeUnit.MILLISECONDS.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放锁.." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello...";
    }

    /**
     * 保证一定能读到最新数据，修改期间，写锁是一个排它锁（互斥锁、独享锁），读锁是一个共享锁
     * 写锁没释放读锁必须等待
     * 读 + 读 ：相当于无锁，并发读，只会在Redis中记录好，所有当前的读锁。他们都会同时加锁成功
     * 写 + 读 ：必须等待写锁释放
     * 写 + 写 ：阻塞方式
     * 读 + 写 ：有读锁。写也需要等待
     * 只要有读或者写的存都必须等待
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String write() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("ReadWriteLock");
        lock.writeLock().lock();
        System.out.println("获取写锁...开始写" + Thread.currentThread().getId());
        try {
            TimeUnit.MILLISECONDS.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放写锁.." + Thread.currentThread().getId());
            lock.writeLock().unlock();
        }
        return "write...";
    }

    @ResponseBody
    @GetMapping("/read")
    public String read() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("ReadWriteLock");
        lock.readLock().lock();
        System.out.println("获取读锁...开始读" + Thread.currentThread().getId());
        try {
            TimeUnit.MILLISECONDS.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放读锁.." + Thread.currentThread().getId());
            lock.readLock().unlock();
        }
        return "read...";
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可以做分布式限流
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() {
        RSemaphore semaphore = redissonClient.getSemaphore("Semaphore");
        try {
            semaphore.acquire();//获取一个信号、获取一个值,占一个车位
//            boolean b = semaphore.tryAcquire();
//            if(b){
//                System.out.println("获取车位....");
//            }else {
//                return "error";
//            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "park";
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() {
        RSemaphore semaphore = redissonClient.getSemaphore("Semaphore");
        semaphore.release();//释放一个车位
        return "go";
    }

    /**
     * 放假、锁门
     * 1班没人了
     * 5个班，全部走完，我们才可以锁大门
     * 分布式闭锁
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch lockDoor = redissonClient.getCountDownLatch("lockDoor");
        lockDoor.trySetCount(5);
        lockDoor.await();//等待闭锁完成
        return "放假了...";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch lockDoor = redissonClient.getCountDownLatch("lockDoor");
        lockDoor.countDown();
        return id + "班的人都走了...";
    }
}
